<?php
namespace Lib\Wx;
use Curl\Curl;
use Think\Log;

/**
 * Created by PhpStorm.
 * User: lazycao
 * Date: 2017/11/28 0028
 * Time: 9:27
 */
class Auth{
    protected $appid;
    protected $secret;
    protected $wx_url;
    function __construct()
    {
        $this->appid = C('WX_appID');
        $this->secret =  C('WX_appsecret');
        $this->wx_url = 'https://open.weixin.qq.com';
        $this->wx_url1 = 'https://api.weixin.qq.com';


    }

    function getCode($redirect,$state=''){

        $url = '%HTTP_URL%/connect/oauth2/authorize?appid=%APP_ID%&redirect_uri=%REDIRECT_URI%&response_type=code&scope=%SCOPE%&state=%STARE%#wechat_redirect';

        $url = str_replace(
            array('%HTTP_URL%','%APP_ID%','%REDIRECT_URI%','%SCOPE%','%STARE%'),
            array($this->wx_url,$this->appid,urlencode($redirect),'snsapi_userinfo',$state),
//            array($this->wx_url,$this->appid,urlencode($redirect),'snsapi_base',$state),
            $url
        );

//        $curl = new Curl();
//        $res = $curl->get($curl);
        return $url;
    }
    function getAccessToken($code){
        $url = sprintf('%s/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code',$this->wx_url1,$this->appid,$this->secret,$code);
        $res = curl_request($url);
        Log::write('微信获取accessToken'.$res,LOG::INFO);
        return $res;
    }
    function refreshAccessToken($refresh_token){
        $url = sprintf('%s/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s',$this->wx_url1,$this->appid,$refresh_token);

        $res = curl_request($url);
        Log::write('微信刷新accessToken'.$res,LOG::INFO);
        return $res;
    }
    function getUserInfo($token,$openid){

        $url = sprintf('%s/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN',$this->wx_url1,$token,$openid);
        $res = curl_request($url);
        Log::write('获取用户信息'.$res,LOG::INFO);
        return $res;
    }
    function verifyAccessToken(){

    }

    function auth($code){
        $res = $this->getAccessToken($code);
        $res = json_decode($res,true);

        /*$res = $this->refreshAccessToken($res['refresh_token']);
        $res = json_decode($res,true);*/
        $res = $this->getUserInfo($res['access_token'],$res['openid']);
        $res = json_decode($res,true);
        return $res;
    }
}